import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions'
import { useHistory } from 'react-router-dom'

import './index.scss'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()

  const onFinish = (values) => {
    dispatch(login({ mobile: values.mobile, code: values.code }))

    message.success('登录成功', 1.5, () => {
      // 登录成功后跳转到首页
      history.replace('/home')
    })
  }
  return (
    <div className="login">
      <Card bordered={false} className="login-wrapper">
        <img className="logo" src={logo} alt="" />

        {/* 登录表单 */}
        <Form
          size="large"
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            remember: true,
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: '手机号为必填项',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不正确',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input maxLength={11} placeholder="请输入手机号码" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '验证码为必填项',
              },
              {
                len: 6,
                message: '验证码格式不正确',
                validateTrigger: 'onBlur',
              },
            ]}
          >
            <Input maxLength={6} placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked">
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
